package com.zhxx.book.controller;

import cn.hutool.core.util.ObjectUtil;
import com.zhxx.book.entity.User;
import com.zhxx.book.service.IUserService;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Author Alex
 * @Date 2022-11-14 11:16
 */
@RestController
@RequestMapping("/user")
public class UserController {
   @Autowired
   private IUserService userService;

   @GetMapping
   public List<User> list() {
      return userService.list();
   }

   @PostMapping
   public Boolean add(@RequestBody User user) {
      if(ObjectUtil.isEmpty(user) || ObjectUtil.isEmpty(user.getId())) {
         return false;
      }

      User userEntity = userService.getById(user.getId());
      // 如歌用户id为空，说明第一次登录，保存用户信息
      if(ObjectUtil.isEmpty(userEntity)) {
         return userService.save(user);
      }
      // 更新用户信息
      return userService.updateById(userEntity);
   }

   @PutMapping
   public Boolean update(@RequestBody User user) {
      return userService.updateById(user);
   }

   @DeleteMapping("/{id}")
   public Boolean delete(@PathVariable Long id) {
      return userService.removeById(id);
   }
}
